package cn.xiaoming.car.server.controller;


import cn.xiaoming.car.server.ex.ServiceException;
import cn.xiaoming.car.server.jsonresult.ServiceCode;
import cn.xiaoming.car.server.pojo.BackOrderInfo;
import cn.xiaoming.car.server.pojo.PayOrderInfo;
import cn.xiaoming.car.server.service.IPayService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("/pay")
public class PayController {
    private final String APP_ID = "9021000123601252";
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCRjhsn0WVvcm+Wfo7sZw2saxHREORbPSgzqwaH54t8As5nv1orSGXRZACWn7EdRBWOUEolOrW9y4SgmBdCiYDPTBA+1CleRBvwaM27YlnktA6W7/kSOvwlqdh7r85EjSYcV+d69kMLPD/C3VWUW5SeZ4jcMMsDop7wZzAyjKOz9hNKgOOSMCYI0h+TRZ0TT6e8sivB+zzV1whqnC4RE9tmYQwp8ioACpgaxBwx0L3oCPaHIMTxL6WBqXUT++u0LQhTfZ/BdlyNIuZYv7HOfHh9VHrffjNFIRQZCO9xAwUK0seL2n5rAW1WW3Ixgb0+YafLaqhgi9Jv8qyXp2tlAmVPAgMBAAECggEASu5HGIZ5m5fjziu01ApxRZORBnmVtUqUiZS/tfMDIYIoU8x0VNfeYp8Clof7G7/TAQJgSS4iJWTCEBJ71usGfrD/o/iAm2CgqXCqiI6nDE+NOzKqnDH1YEZBhdsJasznE6xFJE3mUcBgaqaaydcje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SET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt2dEucFp1h1WP5hoM86bCHVqLmI7OEwp4YpV4sUj3Qb2r1pqtQENPOUbBR/7Kx3OkVSGXiud3Aftk+S+nPNDI/1X6KP2uq5fIDLulNhP1hqRTHD5CUt9j8K39B0ugKyZEVGFf72s1hSxlyylTetPYQzrLX9w8QPdtwQbxszKTEyUPCmQJb0AQFYjxP1W1V5OACNOrgUEQsSHsciNl2x7yEzdVXZbLZTjejtZ+spUPEW3p+BRI1+5VZKSfikp1tyWZmWhs0K1zEqpUVFrfOrjTpwRBDjKojlhc0H1xWQvJbpIHCnRiojgVBbHnkTi2wyhPpgc+pWGfaFEKuuOayyMPwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";

    @Value("${xiaoming.payment.natappUrl}")
    private String natappUrl;
    @Value("${xiaoming.payment.localHtmlUrl}")
    private String localHtmlUrl;

    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = natappUrl+"/xiaoming-pay/pay/return";//先跳转，需要post
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = localHtmlUrl;


    @Autowired
    IPayService payService;


    @GetMapping("/alipay/{orderId}")
    public void alipay(@PathVariable String orderId, HttpServletResponse httpResponse) throws IOException {
        log.debug("uuid:{}",orderId);
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //根据订单编号,查询订单相关信息
        //Order order = payService.selectById(orderId);
        PayOrderInfo orderInfo = payService.selectById(orderId);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderInfo.getId();//orderId.toString();//order.getOrderId().toString();
        //付款金额，必填
        String total_amount = orderInfo.getPayMoney().toString();//order.getOrderPrice().toString();
        //订单名称，必填
        String subject =  orderInfo.getName() ;// order.getOrderName();
        //商品描述，可空
        String body = orderInfo.getBody();
        //设置订单状态
        /*log.debug("订单状态：{}",orderInfo.getStatus().toString());
        String order_state=orderInfo.getStatus().toString();*/

        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                /*+ "\"order_state\":\""+ order_state +"\","*/
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        log.debug("成功发起支付请求了");
        //System.out.println("测试成功了，有接收到请求");
    }

    @RequestMapping(value = "/return", method = RequestMethod.POST)
    public String firstReturn(HttpServletRequest request) throws AlipayApiException {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")){
            log.debug("================成功异步回调==========================");
            Map<String,String> params=new HashMap<>();
            Map<String,String[]> requestParams=request.getParameterMap();
            for (String name:requestParams.keySet()){
                params.put(name,request.getParameter(name));
                log.debug("{}={}",name,request.getParameter(name));
            }
            String sign=params.get("sign");
            String content=AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature=AlipaySignature.rsa256CheckContent(content,sign,ALIPAY_PUBLIC_KEY,CHARSET);
            if (checkSignature){
                log.debug("================交易信息=============================");
                log.debug("交易名称：{}",params.get("subject"));
                log.debug("交易状态：{}",params.get("trade_status"));
                log.debug("支付宝交易凭证号：{}",params.get("trade_no"));
                log.debug("商户订单号：{}",params.get("out_trade_no"));
                log.debug("交易金额：{}",params.get("total_amount"));
                log.debug("买家在支付宝唯一id：{}",params.get("buyer_id"));
                log.debug("买家付款时间：{}",params.get("gmt_payment"));
                log.debug("买家付款金额：{}",params.get("buyer_pay_amount"));
                /*log.debug("获取的订单状态：{}",params.get("order_state"));*/
                //设置支付宝返回信息
                BackOrderInfo backOrderInfo=new BackOrderInfo()
                        .setName(params.get("subject"))
                        .setTradeStatus(params.get("trade_status"))
                        .setTradeNo(params.get("trade_no"))
                        .setOutTradeNo(params.get("out_trade_no"))
                        .setPayMoney(params.get("total_amount"))
                        .setBuyerTradeNo(params.get("buyer_id"))
                        .setGmt_payment(params.get("gmt_payment"))
                        .setBuyerPayMoney(params.get("buyer_pay_amount"));
                        /*.setOrderState(Integer.parseInt(params.get("order_state")));*/
                //调用service，在service中回调订单更新信息(状态)
                payService.backUpdateOrderInfo(backOrderInfo);
            }
        }else {
            throw new ServiceException(ServiceCode.ERR_PAY_FAIL,"支付异常");
        }
        return "ok";
    }



}
